package com.sum.tea.ui

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.SimpleAdapter
import androidx.lifecycle.lifecycleScope
import com.sum.tea.base.BaseMvvmFragment
import com.sum.common.bean.ReadMode
import com.sum.common.bean.Stats
import com.sum.common.bean.TagInfo
import com.sum.common.utils.LogU
import com.sum.common.utils.SoundUtils
import com.sum.tea.R
import com.sum.tea.databinding.ActivityLabelBinding
import com.sum.tea.viewmodel.LabelViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.sample
import kotlinx.coroutines.launch
import java.util.Collections

class LabelFragment : BaseMvvmFragment<ActivityLabelBinding, LabelViewModel>() {
    private var isTidColumnVisible = true
    private val updateFlow = MutableStateFlow<List<TagInfo>>(emptyList())
    private val adapterList = Collections.synchronizedList(mutableListOf<Map<String, Any>>())

    private val tagAdapter by lazy {
        SimpleAdapter(
            requireContext(),
            adapterList,
            R.layout.table_row,
            arrayOf("serialNumber", "epcId", "tid", "count", "rssi"),
            intArrayOf(R.id.cell1, R.id.cell2, R.id.cell5, R.id.cell3, R.id.cell4)
        ).apply {
            viewBinder = TagViewBinder()
        }
    }

    private val broadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                BROADCAST_ACTION_UHF_UP, BROADCAST_ACTION_KEY_DOWN -> {
                    try {
                        lifecycleScope.launch(Dispatchers.Main) {
                            handleBroadcastAction()
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "Error handling broadcast action", e)
                    }
                }
            }
        }
    }

    private fun handleBroadcastAction() {
        with(mBinding) {
            when {
                btnStart.isEnabled -> btnStart.performClick()
                btnStop.isEnabled -> btnStop.performClick()
                else -> {}
            }
        }
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        val headerView = layoutInflater.inflate(R.layout.table_row, null)
        mBinding.listview.addHeaderView(headerView, null, false)

        initializeViews()
        initializeSound()
        setupScrolling()
        observeViewModel()
        setupClickListeners()
    }

    private fun initializeViews() {
        with(mBinding) {
            // 初始化ListView
            listview.adapter = tagAdapter

            // 初始状态设置
            btnStop.isEnabled = false

            // 初始化CheckBox状态
            ckSeconds.isChecked = false
            ckOncelabel.isChecked = false
            ckGrouptid.isChecked = false
        }
    }

    private fun initializeSound() {
         SoundUtils.initSoundPool(requireContext())
    }

    private fun setupScrolling() {
        with(mBinding) {
            // 设置水平滚动视图的触摸事件
            horizontalScrollView.setOnTouchListener { _, _ ->
                nestedScrollView.requestDisallowInterceptTouchEvent(true)
                false
            }

            // 设置列表视图的触摸事件
            listview.setOnTouchListener { _, _ ->
                nestedScrollView.requestDisallowInterceptTouchEvent(true)
                false
            }

            // 设置嵌套滚动视图的触摸事件
            nestedScrollView.setOnTouchListener { _, _ ->
                nestedScrollView.requestDisallowInterceptTouchEvent(false)
                false
            }
        }
    }

    private fun setupClickListeners() {
        with(mBinding) {
            btnStart.setOnClickListener { handleStart() }
            btnStop.setOnClickListener { handleStop() }
            btnClear.setOnClickListener { handleClear() }

            ckOncelabel.setOnCheckedChangeListener { _, isChecked ->
                mViewModel.setSingleLabelMode(isChecked)
            }

            ckGrouptid.setOnCheckedChangeListener { _, isChecked ->
                mViewModel.setGroupTidMode(isChecked)
                isTidColumnVisible = isChecked
                tagAdapter.notifyDataSetChanged()
            }
        }
    }

    private fun handleStart() {
        with(mBinding) {
            btnStart.isEnabled = false
            btnStop.isEnabled = true

            val readMode = when {
                ckOncelabel.isChecked -> ReadMode.NORMAL
                ckGrouptid.isChecked -> ReadMode.GROUP_TID
                else -> ReadMode.FAST
            }

            if (ckSeconds.isChecked) {
                durationSeconds.text.toString().toIntOrNull()?.let { seconds ->
                    startCountdown(seconds)
                }
            }

            mViewModel.startReading(readMode)
        }
    }

    private fun handleStop() {
        with(mBinding) {
            btnStart.isEnabled = true
            btnStop.isEnabled = false
            mViewModel.stopReading()
        }
    }

    private fun handleClear() {
        adapterList.clear()
        mViewModel.clearData()
    }

    private fun startCountdown(seconds: Int) {
        lifecycleScope.launch {
            repeat(seconds) { second ->
                delay(1000)
                mBinding.tvTimer.text = (second + 1).toString()
            }
            handleStop()
        }
    }

    private fun observeViewModel() {
        mViewModel.tagList.observe(viewLifecycleOwner) { tags ->
            updateTagListView(tags)
        }

        mViewModel.stats.observe(viewLifecycleOwner) { stats ->
            updateStats(stats)
        }

        mViewModel.timerValue.observe(viewLifecycleOwner) { value ->
            mBinding.tvTimer.text = value.toString()
        }
    }

    private fun updateTagListView(tags: List<TagInfo>) {
        synchronized(adapterList) {  // 确保原子性
            try {
                val listItems = tags.map { tag ->
                    mapOf(
                        "serialNumber" to tag.serialNumber,
                        "epcId" to tag.epc,
                        "tid" to tag.tid,
                        "count" to tag.count,
                        "rssi" to tag.rssi
                    )
                }
                SoundUtils.playSound()
                adapterList.clear()
                adapterList.addAll(listItems)
                tagAdapter.notifyDataSetChanged()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun updateStats(stats: Stats) {
        with(mBinding) {
            tvFrames.text = stats.tagCountPerSecond.toString()
            tvNumbertag.text = stats.totalTags.toString()
            tvCardreading.text = stats.totalCount.toString()
        }
    }

    inner class TagViewBinder : SimpleAdapter.ViewBinder {
        override fun setViewValue(view: View, data: Any?, textRepresentation: String?): Boolean {
            return false
        }
    }

    override fun onResume() {
        super.onResume()
        registerBroadcastReceiver()
    }


    override fun onPause() {
        super.onPause()
        unregisterBroadcastReceiver()
        handleStop()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        SoundUtils.release()
    }

    private fun registerBroadcastReceiver() {
        IntentFilter().apply {
            addAction(BROADCAST_ACTION_UHF_UP)
            addAction(BROADCAST_ACTION_KEY_DOWN)
            requireActivity().registerReceiver(broadcastReceiver, this)
        }
    }

    private fun unregisterBroadcastReceiver() {
        requireActivity().unregisterReceiver(broadcastReceiver)
    }

    companion object {
        private const val BROADCAST_ACTION_UHF_UP = "com.android.action.keyevent.KEYCODE_KEYCODE_UHF_UP"
        private const val BROADCAST_ACTION_KEY_DOWN = "com.barcode.android.KEY_DOWN"
    }
}